package com.yunshipei.common;

import android.text.TextUtils;

import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.utils.YspLogUtils;
import com.yunshipei.db.green.AppStatistics;
import com.yunshipei.db.green.AppStatisticsDao;
import com.yunshipei.manager.EnterDbManager;

import org.json.JSONArray;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import de.greenrobot.dao.query.Query;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 处理发送埋点信息，上传日志信息等操作
 */
public class SendManager {

    //发送埋点信息
    public void sendPoint() {
        final AppStatisticsDao statisticsDao = EnterDbManager.getInstances().getAppStatisticsDao();
        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(FlowableEmitter<String> e) throws Exception {
                Query<AppStatistics> query = statisticsDao.queryBuilder().build();
                List<AppStatistics> appList = query.list();
                JSONArray jsonArray = new JSONArray();
                if (appList != null && appList.size() > 0) {
                    for (AppStatistics appStatistics : appList) {
                        JSONObject jsonObject = new JSONObject();
                        /**
                         *因为companyId 和url 这两个字段传错了，导致埋点数据无法发送，这里做下之前版本兼容
                         * 如果之前版本版companyId 和 url 这两个字段对调
                         */
                        if (!TextUtils.isEmpty(appStatistics.getCompanyId()) &&
                                (appStatistics.getCompanyId().contains("http")
                                || appStatistics.getCompanyId().contains("enterplorer")
                                || appStatistics.getCompanyId().contains("://")
                                )) {
                            jsonObject.put("companyId", appStatistics.getUrl());
                            jsonObject.put("url", appStatistics.getCompanyId());
                        }else{
                            jsonObject.put("url", appStatistics.getUrl());
                            jsonObject.put("companyId", appStatistics.getCompanyId());
                        }
                        jsonObject.put("uuid", appStatistics.getUuid());
                        jsonObject.put("title", appStatistics.getTitle());
                        jsonObject.put("timeStamp", appStatistics.getTimeStamp());
                        jsonObject.put("appId", appStatistics.getAppId());
                        jsonObject.put("departmentId", appStatistics.getDepartmentId());
                        jsonArray.put(jsonObject);
                    }
                }
                if (jsonArray.length() > 0) {
                    e.onNext(jsonArray.toString());
                } else {
                    e.onError(new XCloudException("无埋点信息..."));
                }
            }
        }, BackpressureStrategy.BUFFER).flatMap(new Function<String, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(String s) throws Exception {
                return HttpMethods.getInstance().pointsFlowable(s);
            }
        }).flatMap(new Function<JSONObject, Publisher<Boolean>>() {
            @Override
            public Publisher<Boolean> apply(JSONObject jsonObject) throws Exception {
                int status = jsonObject.optInt("status", 0);
                if (status == 1) {
                    statisticsDao.deleteAll();
                    return Flowable.just(true);
                }
                return Flowable.error(new XCloudException(jsonObject.optString("message", "未知错误信息...")));
            }
        }).subscribeOn(Schedulers.io()).unsubscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                YspLogUtils.d("埋点发送失败：" + throwable);
            }
        });
    }

    //发送适配的日志
    public void sendAdapterLog(String companyName, String userName) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss", Locale.CHINA);
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String time = formatter.format(curDate);
        String fileName = companyName + "+" + userName + "+" + time + ".log";
        YspLogUtils.uploadLog(fileName);
    }
}
